//
//  RegisterViewController.m
//  iMessage
//
//  Created by kare on 14-3-7.
//  Copyright (c) 2014年 kare. All rights reserved.
//

#import "RegisterViewController.h"
#import "HelpPro.h"
#import "ShowMsgBox.h"
#import "ASIFormDataRequest.h"
#import "ManagerObjectData.h"
#import "UserInformationViewController.h"
#import "notify.h"

@interface RegisterViewController ()
@property (nonatomic ,weak) IBOutlet UITextField *ui_registerName;
@property (nonatomic ,weak) IBOutlet UITextField *ui_registerPasswd;

@end

@implementation RegisterViewController

- (IBAction)onCancel:(id)sender
{
//    if (self.navigationController)
//    {
        [self.navigationController popViewControllerAnimated:YES];
//    NSNotificationCenter
//    }
//    else
//    {
//        [self dismissModalViewControllerAnimated:YES];
//    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)onSubmit:(id)sender
{
    [self onHideKeyBoard];
    
    
    if (!validateMobile(self.ui_registerName.text))
    {
        showView(@"手机号码不正确");
        double delayInSeconds = .8;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.ui_registerName becomeFirstResponder];
        });
        
        return ;
    }
    else if([self.ui_registerPasswd.text length] == 0)
    {
        showView(@"密码不能为空");
        
        double delayInSeconds = .8;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.ui_registerPasswd becomeFirstResponder];
        });
        return ;
    }
    
    [self onRegister];
}

- (void)onHideKeyBoard
{
    if ([self.ui_registerPasswd isFirstResponder])
    {
        [self.ui_registerPasswd resignFirstResponder];
    }
    if ([self.ui_registerName isFirstResponder])
    {
        [self.ui_registerName resignFirstResponder];
    }
}


- (void)onRegister
{
    showViewInView(self.view,@"请求中......");
    
    NSString *urlString = [NSString stringWithFormat:@"%@register",BASICE_URL_TOIMESSAGE];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //    NSLog(@"urlString = %@",urlString);
    
    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [requestForm setPostValue:self.ui_registerPasswd.text forKey:@"password"];
    [requestForm setPostValue:self.ui_registerName.text forKey:@"mobile"];
    [requestForm startSynchronous];
    
    hideViewInView(self.view);
    
//    NSLog(@"[requestForm responseData] = %@",[requestForm responseData]);
    
//    NSLog(@"ManagerObjectData %@\n",[ManagerObjectData getCurrentData:[requestForm responseData]]);
    
//    NSString *str =  [[ManagerObjectData getCurrentData:[requestForm responseData]] objectForKey:@"msg"];

    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if ([ManagerObjectData getCurrentData:[requestForm responseData]] != nil && [[[ManagerObjectData getCurrentData:[requestForm responseData]] objectForKey:@"code"] intValue] != 1000)
        {
            NSDictionary *dic = [[ManagerObjectData getCurrentData:[requestForm responseData]] objectForKey:@"data"];
            
            NSLog(@"dic =%@",dic);
            
            if (dic != nil)
            {
                NSString *userToken = [dic  objectForKey:@"token"];
                
                int  Level = [[dic  objectForKey:@"level"] intValue];
                
                NSString *mobile = [dic  objectForKey:@"mobile"];
                
                [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:Level] forKey:@"UserLevel"];
                [[NSUserDefaults standardUserDefaults] setObject:userToken forKey:@"UserToken"];
                [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"UserMobile"];
                [[NSUserDefaults standardUserDefaults] setObject:[ManagerObjectData getCurrentPressDate] forKey:@"UserRegisterTimer"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                NSArray *array = [NSArray arrayWithObject:userToken];
                [array writeToFile:PLISTRURL atomically:YES];
                
                // 触发通知了
                notify_post("com.betetui.settings_changed");
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self goUserCenter];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                showView(@"注册失败！");
            });
        }
    });
    
}


- (void)goUserCenter
{
    UserInformationViewController *user = [[UserInformationViewController alloc] initWithNibName:@"UserInformationViewController" bundle:nil];
    [self.navigationController pushViewController:user animated:YES];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"sfsdf");
    [textField resignFirstResponder];
    [self onSubmit:nil];
    return YES;
}


@end
